import * as monaco from 'monaco-editor';
import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker';
import htmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker';
import cssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker';

self.MonacoEnvironment = {
	getWorker(workerId, label) {
		if (label === 'json') {
			return new jsonWorker();
		}
		if (label === 'typescript' || label === 'javascript') {
			return new tsWorker();
		}
		if (['html', 'handlebars', 'razor'].includes(label)) {
			return new htmlWorker();
		}
		if (['css', 'scss', 'less'].includes(label)) {
			return new cssWorker();
		}
		return new editorWorker();
	}
};

export const useMonacoEditor = (language = 'javascript') => {
	let monacoEditor = null;
	let initReadOnly = false;
	const el = shallowRef(null);

	// 格式化
	const onFormatDoc = async () => {
		await monacoEditor?.getAction('monacoEditor.action.formatDocument')?.run();
	};

	// 更新
	const updateVal = (val) => {
		nextTick(async () => {
			monacoEditor?.setValue(val);
			initReadOnly && monacoEditor?.updateOptions({ readOnly: false });
			await onFormatDoc();
			initReadOnly && monacoEditor?.updateOptions({ readOnly: true });
		});
	};

	// 创建实例
	const createEditor = (editorOption = {}) => {
		if (!el.value) return;
		initReadOnly = !!editorOption.readOnly;
		// 创建
		monacoEditor = monaco.editor.create(el.value, {
			language,
			// 是否启用预览图
			minimap: { enabled: false },
			// 圆角
			roundedSelection: true,
			// 主题
			theme: $store.user.themeName == 'dark' ? 'vs-dark' : 'vs',
			// 主键
			multiCursorModifier: 'ctrlCmd',
			// 滚动条
			scrollbar: {
				verticalScrollbarSize: 8,
				horizontalScrollbarSize: 8
			},
			// 行号
			lineNumbers: 'off',
			// tab大小
			tabSize: 2,
			//字体大小
			fontSize: 16,
			// 控制编辑器在用户键入、粘贴、移动或缩进行时是否应自动调整缩进
			autoIndent: 'advanced',
			// 自动布局
			automaticLayout: true,
			selectOnLineNumbers: true, // 显示行号
			...editorOption
		});

		return monacoEditor;
	};

	// 卸载
	onBeforeUnmount(() => {
		if (monacoEditor) monacoEditor.dispose();
	});

	return {
		el,
		updateVal,
		getEditor: () => monacoEditor,
		createEditor,
		onFormatDoc
	};
};
